
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

/**
 * alibaba OSS 操作
 *
 * @author hebad90@163.com
 * @date 2013年8月31日
 */
public class OSSUtil {

    public OSSClient client() {
        // endpoint以杭州为例，其它region请按实际情况填写
        String endpoint ="oss-cn-shanghai.aliyuncs.com";
        String accessKeyId ="LTAI8kFxkZ1hFaB2";
        String accessKeySecret = "OUzEynxrGMUADTU6EFYNJxdMIaDpHH";
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        return ossClient;
    }


    public static void main(String[] args) {
        try {

            OSSUtil ossUtil = new OSSUtil();
            OSSClient client = ossUtil.client();
            //client.setBucketAcl("superseller-amazon-data",CannedAccessControlList.parse("public-read"));
            List<Bucket> buckets = client.listBuckets();

            for (Bucket bucket : buckets) {
                System.out.println(bucket.getName());
            }
//            Connection connection = JdbcUtil.getConnection();
//            Statement statement = connection.createStatement();
//            ResultSet rs = statement.executeQuery("select * from amazon_json_schema");
//            while(rs.next()){
//                String name = rs.getString("name");
//                String schema = rs.getString("schema");
//                ObjectMetadata metadata = new ObjectMetadata();
//                metadata.setContentLength(schema.getBytes().length);
//                metadata.setContentType("application/json");
//                PutObjectResult result = client.putObject("superseller-amazon-data", "schema/"+name,new ByteArrayInputStream(schema.getBytes()), metadata);
//            }
            String[] attrs  = new String[]{"us.json","ca.json","mx.json"};
            //String[] attrs  = new String[]{"ebayus.json"};

            for (String attr :attrs){
                String content = Files.toString(new File("/Users/donar/"+attr), Charsets.UTF_8);
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentLength(content.getBytes().length);
                metadata.setContentType("application/json");
                PutObjectResult result = client.putObject("superseller-amazon-data", "search/"+attr,new ByteArrayInputStream(content.getBytes()), metadata);

            }
//            File file = new File("MEXICO.json");
//            ObjectMetadata metadata = new ObjectMetadata();
//            metadata.setContentLength(file.length());
//            metadata.setContentType("application/json");
//            PutObjectResult result = client.putObject("superseller-amazon-data", "schema/mx.json",new FileInputStream(file), metadata);
//            //System.out.println(result);
            // String key=  OSSUtil.uploadFile("phone-detail","yukilovesummer", "/Users/zhongl/Desktop/test.csv");
            // System.out.println(key);

            //  downLoadFile("phone-detail","测试卖家381696371","/Users/zhongl/Desktop");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 如果Bucket不存在，则创建它。
     * @param bucketName
     * @return 是否创建成功
     */
    /*public static boolean createBucket(String bucketName) {
		boolean result=true;
		if(client().doesBucketExist(bucketName)) {
			return result;
		}
		Bucket bucket=client().createBucket(bucketName);
		updateBucketAccess(bucketName, CannedAccessControlList.PublicRead);
		if(bucket==null) result=false;
		return result;
	}*/

    /**
     * 修改Bucket 的权限
     * @param bucketName: 针对哪个BucketName
     * @param access : CannedAccessControlList的常量(Private,PublicRead,PublicReadWrite)
     *   public-read-write: 任何人（包括匿名访问）都可以对该bucket中的object进行上传、下载和删除操作；所有这些操作产生的费用由该bucket的创建者承担，请慎用该权限。
     *	 public-read: 只有该bucket的创建者可以对该bucket内的Object进行写操作（包括上传和删除）；任何人（包括匿名访问）可以对该bucket中的object进行读操作。
     *   private: 只有该bucket的创建者才可以访问此Bukcet。其他人禁止对此Bucket做任何操作。
     */
	/*public static void updateBucketAccess(String bucketName, CannedAccessControlList access) {
		client().setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
	}*/

    /**
     * 上传至oss
     *
     * @param bucketName                              phone-detail
     * @param key:就是你在oss上面存储的名字，如果                   a/b/c.txt,则自动回创建目录.注意上传的是默认是在bucket下面，不要以/开头
     * @param path:需要上传的文件路径,可以是本地，也可以是http://形式的URL。
     * @return
     * @throws IOException
     */
    public String uploadFile(String bucketName, String key, String path) throws IOException {
        if (key != null && key.startsWith("/")) {
            key = key.substring(1);
        }
        InputStream is = null;
        try {
            ObjectMetadata objectMeta = new ObjectMetadata();
            if (path.startsWith("http:")) {
                URL u = new URL(path);
                is = u.openStream();
                objectMeta.setContentLength(u.openConnection().getContentLength());
            } else {
                File file = new File(path);
                is = new FileInputStream(file);
                //必须设置
                objectMeta.setContentLength(file.length());
            }
            client().putObject(bucketName, key, is, objectMeta);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                is.close();
                is = null;
            }
        }
        return "oss-cn-shanghai.aliyuncs.com" + bucketName + "/" + key;
    }

    /**
     * 从	oss下载至目标
     *
     * @param bucketName
     * @param key:
     * @param target:下载到哪里
     * @return 下载的目的地
     */
    public String downLoadFile(String bucketName, String key, String target) {
        if (key.startsWith("/")) {
            key = key.substring(1);
        }
        client().getObject(new GetObjectRequest(bucketName, key), new File(target));
        return target;
    }

    /**
     * 从oss下载至目标
     *
     * @param bucketName
     * @param key:
     * @return 下载的目的地
     * @paramtarget:下载到哪里
     */
    public OSSObject downLoadFile(String bucketName, String key) throws OSSException {
        if (key.startsWith("/")) {
            key = key.substring(1);
        }
        OSSObject ossObject = client().getObject(bucketName, key);
        return ossObject;
    }

    /**
     * 从oss服务器上面的一个key获取is
     * @param bucketName
     * @param key
     * @return
     */
	/*private static InputStream getInputStream(String bucketName,String key) {
		if(key.startsWith("/")) {
			key=key.substring(1);
		}
		return client().getObject(new GetObjectRequest(bucketName, key)).getObjectContent();
	}*/

    /**
     * 判断传入的key在给的这个bucketName中是否存在
     *
     * @param bucketName
     * @param key
     * @return
     */
    public boolean isKeyExist(String bucketName, String key) {
        boolean result = true;
        try {
            if (key.startsWith("/")) {
                key = key.substring(1);
            }
            client().getObject(new GetObjectRequest(bucketName, key));
        } catch (OSSException e) {
            result = false;
        }
        return result; //result
    }

    /**
     * 删除一个key
     *
     * @param bucketName
     * @param key
     */
    public void deleteObject(String bucketName, String key) {
        if (isKeyExist(bucketName, key)) {
            if (key.startsWith("/")) {
                key = key.substring(1);
            }
            client().deleteObject(bucketName, key);
        }
    }

    /**
     * 删除一个bucket，如果有子文件都会被删除
     * @param bucketName
     */
	/*public static void deleteBucket(String bucketName) {
		ObjectListing ObjectListing = client().listObjects(bucketName);
        List<OSSObjectSummary> listDeletes = ObjectListing.getObjectSummaries();
        for (int i = 0; i < listDeletes.size(); i++) {
            String objectName = listDeletes.get(i).getKey();
            // 如果不为空，先删除bucket下的文件
            client().deleteObject(bucketName, objectName);
        }
		client().deleteBucket(bucketName);
	}*/

    /**
     * 列出bucket下面的所有文件
     * @param bucketName
     * @return 返回所有文件的全称名字(默认100个Object, 要更多的话设置 MaxKeys)
     */
	/*public static List<String> listObjectFromBucket(String bucketName){
		ObjectListing list=client().listObjects(bucketName);
		List<String> result=new ArrayList<String>();
		for(OSSObjectSummary os : list.getObjectSummaries()) {
			result.add(os.getKey());
		}
		return result;
	}*/

    /**
     * 列出所谓的文件夹下面的所有文件夹
     *
     * @return
     * @parambucketName
     * @paramprefix 哪个个文件夹
     */
	/*public static List<String> listObjectFromPrefix(String bucketName,String prefix) {
		if(prefix.startsWith("/")) {
			prefix=prefix.substring(1);
		}
		ObjectListing list=client().listObjects(bucketName,prefix);
		List<String> result=new ArrayList<String>();
		for(OSSObjectSummary os : list.getObjectSummaries()) {
			result.add(os.getKey());
		}
		return result;
	}*/

    public static void PostFile(String url,String filename, String filepath)  {
        HttpClient httpclient = new DefaultHttpClient();

        HttpPut httppost = new HttpPut(url);
        File file = new File(filepath + File.separator + filename);

        FileEntity reqEntity = new FileEntity(file, "image/jpeg");

        httppost.setEntity(reqEntity);
        reqEntity.setContentType("image/jpeg");
        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity resEntity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            try {
                System.out.println(EntityUtils.toString(resEntity));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (resEntity != null) {
            try {
                resEntity.consumeContent();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        httpclient.getConnectionManager().shutdown();
    }

    public  File getObject(String bucketName,String key,String fileName){
        // 新建GetObjectRequest
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);

        File file = new File("/tmp/"+fileName);

        ObjectMetadata objectMetadata = client().getObject(getObjectRequest, file);
        return file;
    }



}
